package org.Demo;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectDemo {
    public static void main(String[] args) {
        //定义数据源
        DataSource dataSource = new MysqlDataSource();
        // 设置URL，也就是数据库连接字符串
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://localhost:3306/java_text?characterEncoding=utf8&useSSL=false");
        // 设置用户名
        ((MysqlDataSource) dataSource).setUser("root");
        // 设置密码
        ((MysqlDataSource) dataSource).setPassword("123456");

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //连接数据库
            connection = dataSource.getConnection();
            //构造SQL语句
            String sql = "select id, sn, name, qq_mail, classes_id from student";
            //获取SQL预处理对象
            preparedStatement = connection.prepareStatement(sql);
            //执行SQL
            resultSet = preparedStatement.executeQuery();
            //遍历结果集获取数据
            while (resultSet.next()){
                // 7. 读取返回的数据，这里是按照返回的列的顺序去读
                // 学生Id
                int id = resultSet.getInt("id");
                // 学号
                String sn = resultSet.getString("sn");
                // 姓名
                String name = resultSet.getString("name");
                // 邮箱
                String mail = resultSet.getString("qq_mail");
                // 班级编号
                int classesId = resultSet.getInt("classes_id");
                // 打印结果
                System.out.println("Id = " + id + ", 学号 = " + sn + ", 姓名 = " + name + ", 邮箱 = " + mail + ", 班级编号 = " + classesId);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭结果集对象
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            //关闭预处理对象
            if (preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            //关闭连接
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}
